<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title> <!-- 引入 Element Plus 样式 -->
		<link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
		<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- 引入 Vue 3 及 Element Plus 脚本 -->
		<script src="https://unpkg.com/vue@3"></script>
		<script src="https://unpkg.com/element-plus"></script>
		<style scoped>
			.layout-container-demo .el-header {
				position: relative;
				background-color: var(--el-color-primary-light-7);
				color: var(--el-text-color-primary);
			}

			.layout-container-demo .el-aside {
				color: var(--el-text-color-primary);
				background: var(--el-color-primary-light-8);
			}

			.layout-container-demo .el-menu {
				border-right: none;
			}

			.layout-container-demo .el-main {
				padding: 0;
			}

			.layout-container-demo .toolbar {
				display: inline-flex;
				align-items: center;
				justify-content: center;
				height: 100%;
				right: 20px;
			}
		</style>
	</head>
	<body>
		<div id="app">
			<div style="height: 50px;">系统管理>><a href="#">角色权限配置</a></div>
			<el-container class="layout-container-demo" style="height: 600px">
				<el-aside width="300px" style="border: 1px solid black;">
					<el-scrollbar>
						<el-menu>
							<select style="margin-left: 30px;" v-model="selectedRoleId" @change="queryByLike">
								<option value="0" selected disabled>-- 请选择角色 --</option>
								<option value="1">-- 系统管理员 --</option>
								<option value="2">-- 路线管理员 --</option>
								<option value="3">-- 巡检员 --</option>
								<option value="4">-- 消缺员 --</option>
							</select>
							<el-menu-item style="margin-left: 20px;" class="custom-menu-item">系统功能菜单树</el-menu-item>
							<el-menu>
								<el-sub-menu v-for="parentItem in menuItems" :key="parentItem.id"
									:index="parentItem.id">
									<template #title>
										<el-icon>
											<message />
										</el-icon>
										<el-checkbox :model-value="parentItem.checked"
											@change="selectAllChildren(parentItem)" @click.stop>
											{{ parentItem.functionName }}
										</el-checkbox>
									</template>
									<el-menu-item-group
										v-if="parentItem.psFunctionList && parentItem.psFunctionList.length > 0">
										<el-menu-item style="margin-left: 20px;"
											v-for="childItem in parentItem.psFunctionList" :key="childItem.id">
											<el-checkbox :model-value="childItem.checked"
												@change="updateChildItem(parentItem, childItem, $event)">
												{{ childItem.functionName }}
											</el-checkbox>
										</el-menu-item>
									</el-menu-item-group>
								</el-sub-menu>
							</el-menu>
							<div style="margin-left: 50px; height: 30px;">
								<a href="#" @click="caidan()">添加一级菜单</a>
							</div>

						</el-menu>
						<div style="margin-left: 50px; margin-top: 50px;">
							<el-button @click="baocun()">保存配置</el-button>
						</div>
					</el-scrollbar>
				</el-aside>

				<el-container>
					<el-main>
						<div id="myDiv"
							style="border: 1px solid black; width: 800px; height: 598px; margin-left: 10px; display: none;">
							<div style="margin-left: 100px; margin-top: 50px;">
								<h1>新建菜单节点</h1>
								<div style="width: 600px; height: 1px; background-color: black;"></div>
								<br />
								<div>
									父节点：<span v-if="jiedian">{{ jiedian }}</span><span v-else
										style="color: red;">请选择父节点</span>
								</div>
								<br />
								<br />
								<div>
									功能编码：<input type="text" v-model="caidans.functionCode" />
								</div>
								<br />
								<br />
								<div>
									功能名称：<input type="text" v-model="caidans.functionName" />
								</div>
								<br />
								<br />
								<div>
									功能URL：<input type="text" v-model="caidans.funcUrl" />
								</div>
								<br />
								<br />
								<el-form-item label="状态:">
									<el-radio-group v-model="caidans.isStart">
										<el-radio :label="1">启用</el-radio>
										<el-radio :label="0">停用</el-radio>
									</el-radio-group>
								</el-form-item>
								<br />
								<br />
								<div>
									<button @click="adds()">保存</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
									<button @click="fanhui()">返回</button>
								</div>
							</div>
						</div>
					</el-main>
				</el-container>
			</el-container>
		</div>


		<script>
			const {
				createApp
			} = Vue;
			const app = createApp({
				data() {
					return {
						status: 1, // 默认选中启用
						selectedRoleId: 0,
						selectAll: false,
						//父级菜单
						menuItems: [],
						//对比父级菜单
						menuItems2: [],
						aa: {
							functionCode: ''
						},
						jiedian: {
							functionName: '请选择父节点'
						},
						caidans: {
							functionCode: '',
							functionName: '',
							funcUrl: '',
							isStart: 1,
							createdBy: '',
							parentId: '',
							roleId: ''
						},
						userData: {
							username: ''
						},
						psRolePremission: {
							roleId:'',
							functionCode:'',
							createdBy:'',
							isStart:''
						}
					};
				},
				methods: {
					load() {
						$.getJSON("http://127.0.0.1:8080/PsFunction/queryAll", (json) => {
							console.log(json)
							//父级菜单
							this.menuItems = json
						})
					},
					selectAllChildren(parentItem) {
						parentItem.checked = !parentItem.checked;
						for (let childItem of parentItem.psFunctionList) {
							childItem.checked = parentItem.checked;
							// 这里获取子节点的 parentId
							this.caidans.parentId = childItem.parentId;
						}
						// 获取选中的父节点菜单名称
						if (parentItem.checked) {
							this.jiedian = parentItem.functionName;
						} else {
							this.jiedian = ''; // 清空 this.jiedian
						}

						// 添加判断，如果取消选择父节点，则取消选择所有子节点
						if (!parentItem.checked) {
							for (let childItem of parentItem.psFunctionList) {
								childItem.checked = false;
							}
						}
					},
					queryByLike() {
						console.log("选定的角色值为：" + this.selectedRoleId);
						this.caidans.roleId = this.selectedRoleId;
						$.getJSON("http://127.0.0.1:8080/PsRole/queryByLike", {
							id: this.selectedRoleId
						}, (json) => {
							if (json && json.length > 0) {
								this.aa = json.flatMap(item => item.psRolePremissionList.map(item2 => item2
									.functionCode));
								this.updateChildMenuItems();
								this.updateParentMenuItems();
							} else {
								// 如果查询结果为空或没有父级数组，可以在这里添加处理逻辑
								console.log("未找到相关角色信息或父级数组为空");
								// 可以清空相关数据或进行其他操作
								this.aa = [];
								// 清空子级菜单项和父级菜单项
								this.menuItems.forEach(parentItem => {
									parentItem.checked = false;
									parentItem.psFunctionList.forEach(childItem => {
										childItem.checked = false;
									});
								});
							}
						});
					},
					updateChildItem(parentItem, childItem, checked) {
						// 提取所有子菜单项的 functionCode 到一个数组中
						const functionCodes = [].concat(...this.menuItems.map(item => item.psFunctionList.map(item2 =>
							item2.functionCode)));
						// 检查当前子菜单项的 functionCode 是否在 functionCodes 数组中
						if (functionCodes.includes(childItem.functionCode)) {
							childItem.checked = checked;
							this.updateParentMenuItems(); // 更新父级菜单项的选中状态
						}
					},

					updateChildMenuItems() {
						this.menuItems.forEach(parentItem => {
							let allChildrenChecked = true;
							if (parentItem.psFunctionList && parentItem.psFunctionList.length > 0) {
								parentItem.psFunctionList.forEach(childItem => {
									const found = this.aa.includes(childItem.functionCode);
									childItem.checked = found;
									if (!found) {
										allChildrenChecked = false;
									}
								});
								parentItem.checked = allChildrenChecked;
							} else {
								// 如果没有子级数组，手动设置父级数组状态
								parentItem.checked = this.aa.some(code => parentItem.functionCode === code);
							}
						});
					},

					updateParentMenuItems() {
						this.menuItems.forEach(parentItem => {
							if (parentItem.psFunctionList && parentItem.psFunctionList.length >
								0) { // 检查是否存在子菜单项
								const checkedChildren = parentItem.psFunctionList.filter(childItem => childItem
									.checked);
								if (checkedChildren.length === 0) { // 如果没有子菜单项被选中，则不选中父级菜单项
									parentItem.checked = false;
								} else {
									parentItem.checked = checkedChildren.length === parentItem.psFunctionList
										.length;
								}
							}
						});
					},
					caidan() {
						const names = this.jiedian.functionName;
						var div = document.getElementById("myDiv");
						div.style.display = "block"; // 设置显示
					},
					fanhui() {
						var div = document.getElementById("myDiv");
						div.style.display = "none"; // 设置显示
					},
					adds() {
						this.caidans.createdBy = this.userData.username;
						console.log(this.caidans)
						$.getJSON("http://127.0.0.1:8080/PsFunction/add", this.caidans, (json) => {
							this.load();
						})
					},
					baocun() {
						// 检查 roleId 是否为空
						if (!this.caidans.roleId || this.caidans.roleId === 0) {
							alert('请选择角色后再进行保存！');
							return; // 终止保存操作
						}
						this.psRolePremission = {}; // 声明为对象
						
						this.menuItems.forEach(parentItem => {
						  parentItem.psFunctionList.forEach(childItem => {
						    if (childItem.checked) {
						      const selectedItems = {
						        roleId: this.caidans.roleId,
						        functionCode: childItem.functionCode,
						        createdBy: this.userData.username,
						        isStart: this.caidans.isStart
						      };
						
						      // 将选定的权限对象直接添加到 psRolePremission 对象中
						      this.psRolePremission = {
						        roleId: selectedItems.roleId,
						        functionCode: selectedItems.functionCode,
						        createdBy: this.userData.username,
						        isStart: selectedItems.isStart
						      };
						    }
						  });
						});
						console.log(this.psRolePremission);
						$.getJSON("http://127.0.0.1:8080/PsRolePreMissionController/add", this.psRolePremission , (
							json) => {
							console.log(json)
							this.queryByLike(this.psRolePremission.roleId)
						})
					}
				},
				mounted() {
					// 在调用 updateChildMenuItems 方法的地方输出其源代码
					console.log(this.updateChildMenuItems.toString());
					this.userData = JSON.parse(localStorage.getItem('userData'));
					console.log('用户数据:', this.userData);
					this.load()
				}
			})
			app.use(ElementPlus);
			app.mount('#app');
		</script>
	</body>
</html>